package models

import (
	"errors"
	"fmt"
	"reflect"
	"strings"
	"time"

	"gitee.com/lzqysoft/ims/libs"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type Stateinstance struct {
	Id           string        `orm:"column(id);pk"`
	UserId       string        `orm:"column(user_id)"`
	Flowinstance *Flowinstance `orm:"column(flowinstance_id);rel(fk)"`
	State        *State        `orm:"column(state_id);rel(fk)"`
	Busyid       string        `orm:"column(busyid);null"`
	Busyname     string        `orm:"column(busyname);null"`
	Text         string        `orm:"column(text);null"`
	Classname    string        `orm:"column(classname);null"`
	Style        string        `orm:"column(style);type(jsonb);null"`
	Remark       string        `orm:"column(remark);null"`
	Opinions     string        `orm:"column(opinions);null"`
	Approver     string        `orm:"column(approver);null"`
	Result       int           `orm:"column(result);null"`
	Atime        time.Time     `orm:"column(atime);type(timestamp with time zone);null"`
	Status       int           `orm:"column(status)"`
	Isdelete     int           `orm:"column(isdelete)"`
	Ctime        time.Time     `orm:"column(ctime);type(timestamp with time zone)"`
	Creater      string        `orm:"column(creater)"`
	Utime        time.Time     `orm:"column(utime);type(timestamp with time zone)"`
	Updater      string        `orm:"column(updater)"`
}

func (t *Stateinstance) TableName() string {
	return "fsm_stateinstance"
}

func init() {
	orm.RegisterModel(new(Stateinstance))
}

func NewStateinstance() *Stateinstance {
	return &Stateinstance{
		Id:       libs.UUID(),
		Status:   1,
		Isdelete: 0,
		Ctime:    time.Now(),
		Utime:    time.Now(),
	}
}

// AddStateinstance insert a new Stateinstance into database and returns
// last inserted Id on success.
func AddStateinstance(m *Stateinstance) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetStateinstanceById retrieves Stateinstance by Id. Returns error if
// Id doesn't exist
func GetStateinstanceById(id string) (v *Stateinstance, err error) {
	o := orm.NewOrm()
	v = &Stateinstance{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	//if _, err := o.LoadRelated(v, "Role"); err != nil {
	//	return nil, err
	//}
	if _, err := o.LoadRelated(v, "State"); err != nil {
		return nil, err
	}
	//beego.Debug(v)
	beego.Debug(err)
	return v, err
}

// GetAllStateinstance retrieves all Stateinstance matches certain condition. Returns empty list if
// no records exist
func GetAllStateinstance(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []Stateinstance
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateStateinstance updates Stateinstance by Id and returns error if
// the record to be updated doesn't exist
func UpdateStateinstanceById(m *Stateinstance) (err error) {
	o := orm.NewOrm()
	v := Stateinstance{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteStateinstance deletes Stateinstance by Id and returns error if
// the record to be deleted doesn't exist
func DeleteStateinstance(id string) (err error) {
	o := orm.NewOrm()
	v := Stateinstance{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&Stateinstance{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// GetStateByFlowIns 根据流程实例id获取状态
func GetStateByFlowIns(flowid string) (stateInses []Stateinstance, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(State))
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1).Filter("Flowinstance", flowid).RelatedSel()
	_, err = qs.Limit(-1).All(&stateInses)
	return
}
func GetStateByFlowInsReWrite(flowid string) (stateInses []Stateinstance, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance))
	qs = qs.Filter("Isdelete", 0).Filter("Flowinstance", flowid).Filter("Status__lt", 3).RelatedSel()
	_, err = qs.Limit(-1).OrderBy("Ctime").All(&stateInses)
	return
}

// GetStartByFlowIns 根据流程实例id获取开始节点状态
func GetStartByFlowIns(flowid string) (stateIns Stateinstance, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance))
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1).Filter("Flowinstance", flowid).RelatedSel()
	err = qs.Filter("Classname", "start").One(&stateIns)
	return
}

// GetEndByFlowIns 根据流程实例id获取结束节点状态
func GetEndByFlowIns(flowid string) (stateIns Stateinstance, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance))
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1).Filter("Flowinstance", flowid).RelatedSel()
	err = qs.Filter("Classname", "end").One(&stateIns)
	return
}

// GetStateinstanceByFlowInsAndState 根据流程实例id和stateid获取节点实例
func GetStateinstanceByFlowInsAndState(flowid, state_id string) (stateIns Stateinstance, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance))
	qs = qs.Filter("Flowinstance", flowid).Filter("State", state_id)
	qs = qs.RelatedSel()
	err = qs.One(&stateIns)
	if err != nil {
		beego.Error(err)
	}
	return
}

func GetSfCaseBusyDoing(user *User) ([]orm.Params, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", user.Role[0].Id).Filter("Busyname", "sf_case")
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1)
	var l orm.ParamsList
	_, err := qs.Limit(-1).ValuesFlat(&l, "Busyid")
	if err != nil || len(l) < 1 {
		return nil, err
	}
	beego.Debug(l)

	ts := o.QueryTable("sf_case").Filter("Id__in", l).Filter("isdelete", 0).
		OrderBy("-utime").Filter("JyType", user.JdType)
	var e []orm.Params
	_, err = ts.Values(&e)
	return e, err
}
func GetChangeBusyDoing(user *User) ([]orm.Params, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", user.Id).Filter("Busyname", "ims_project_flow")
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1)
	var l orm.ParamsList
	_, err := qs.Limit(-1).ValuesFlat(&l, "Busyid")
	if err != nil || len(l) < 1 {
		return nil, err
	}
	beego.Debug(l)

	ts := o.QueryTable("ims_project").Filter("Id__in", l).Filter("isdelete", 0).OrderBy("-utime")
	var e []orm.Params
	_, err = ts.Values(&e)
	return e, err
}

// GetBusyDoing 根据用户id和业务名称获取待办信息
func GetBusyDoing(user *User, bname string) ([]orm.Params, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", user.Id).Filter("Busyname", bname)
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1)
	var l orm.ParamsList
	_, err := qs.Limit(-1).ValuesFlat(&l, "Busyid")
	if err != nil || len(l) < 1 {
		return nil, err
	}
	beego.Debug(l)

	ts := o.QueryTable(bname).Filter("Id__in", l).Filter("isdelete", 0).OrderBy("-utime")
	var e []orm.Params
	_, err = ts.Values(&e)
	return e, err
}

// GetBusyDoing 根据用户id和业务名称, 业务类型获取待办信息
func GetBusyDoingByType(user *User, bname string, ptype int) ([]orm.Params, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", user.Id).Filter("Busyname", bname)
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1)
	var l orm.ParamsList
	_, err := qs.Limit(-1).ValuesFlat(&l, "Busyid")
	if err != nil || len(l) < 1 {
		return nil, err
	}
	beego.Debug(l)
	beego.Debug(bname)
	//ts := o.QueryTable(bname).Filter("Id__in", l).Filter("isdelete", 0).Filter("Type", ptype).OrderBy("-utime")
	ts := o.QueryTable(bname).Filter("Id__in", l).Filter("isdelete", 0).OrderBy("-utime")
	var e []orm.Params
	_, err = ts.Values(&e)

	if bname != "ims_project" {
		idArray := make([]string, 0)
		for _, v := range e {
			idArray = append(idArray, v["ImsProject"].(string))
		}
		_, err = o.QueryTable("ims_project").Filter("Id__in", idArray).Values(&e)
		beego.Debug(idArray)
		return e, err
	}
	beego.Debug(e)
	return e, err
}

// GetBusyDoing 根据用户id和业务名称, 业务类型获取待办信息

// ReApply 根据用户id和业务id
// 将退回的流程实例和状态实例设置为玩成
func ReApply(userid, busyid string, fi *Flowinstance) (err error) {
	o := orm.NewOrm()
	var stinc Stateinstance
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", userid).Filter("Busyid", busyid)
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1)
	err = qs.One(&stinc)
	stinc.Status = 2
	stinc.Opinions = "重新上报"
	fi.Status = 2
	o.Update(fi)
	return
}

// 终止流程
func StopFlow(user *User, fi *Flowinstance) (err error) {
	fi.Status = 0
	fi.Remark = ""
	fi.Updater = user.Abbr
	fi.Utime = time.Now()
	o := orm.NewOrm()
	_, err = o.Update(fi)
	return
}

// GetBusyFlowing 根据用户id和业务名称获取已处理完成流转中信息
func GetBusyFlowing(user *User, bname string) ([]orm.Params, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", user.Id).Filter("Busyname", bname)
	qs = qs.Filter("Flowinstance__Status", 1)
	qs = qs.Filter("Isdelete", 0).Filter("Status", 2)
	var l orm.ParamsList
	_, err := qs.Limit(-1).ValuesFlat(&l, "Busyid")
	if err != nil || len(l) < 1 {
		return nil, err
	}
	ts := o.QueryTable(bname).Filter("Id__in", l).OrderBy("-utime")
	if bname == "sf_sfyy" {
		ts = ts.Filter("jy_type", user.JdType)
	}
	var e []orm.Params
	_, err = ts.Values(&e)
	return e, err

}

// GetBusyFlowing 根据用户id和业务名称获取已处理完成流转中信息
func GetBusyFlowingByType(user *User, bname string, ptype int) ([]orm.Params, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", user.Id).Filter("Busyname", bname)
	qs = qs.Filter("Flowinstance__Status", 1)
	qs = qs.Filter("Isdelete", 0).Filter("Status", 2)
	var l orm.ParamsList
	_, err := qs.Limit(-1).ValuesFlat(&l, "Busyid")
	if err != nil || len(l) < 1 {
		return nil, err
	}
	beego.Debug(l)
	ts := o.QueryTable(bname).Filter("Id__in", l).Filter("Type", ptype).OrderBy("-utime")
	//if bname == "sf_sfyy" {
	//	ts = ts.Filter("jy_type", user.JdType)
	//}
	var e []orm.Params
	_, err = ts.Values(&e)
	return e, err

}

// GetBusyFlowing 根据用户id和业务名称获取已处理完成流转中信息
func GetBusyFlowingByUser(user *User, bname string) ([]orm.Params, error) {
	o := orm.NewOrm()
	//qs := o.QueryTable(new(Stateinstance)).Filter("UserId", user.Id).Filter("Busyname", bname)
	//qs = qs.Filter("Flowinstance__Status", 1)
	//qs = qs.Filter("Isdelete", 0).Filter("Status__gte", 2)
	//var l orm.ParamsList
	//_, err := qs.Limit(-1).ValuesFlat(&l, "Busyid")
	//if err != nil || len(l) < 1 {
	//	return nil, err
	//}
	ts := o.QueryTable(bname).Filter("cid", user.Id).Filter("status__gte", 2).OrderBy("-utime")
	//if bname == "sf_sfyy" {
	//	ts = ts.Filter("jy_type", user.JdType)
	//}
	var e []orm.Params
	_, err := ts.Values(&e)
	return e, err

}

// GetBusyFinish 根据用户id和业务名称获取流程结束信息
func GetBusyFinish(user *User, bname string) ([]orm.Params, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", user.Id).Filter("Busyname", bname)
	qs = qs.Filter("Flowinstance__Status", 2)
	qs = qs.Filter("Isdelete", 0).Filter("Status", 2)
	var l orm.ParamsList
	_, err := qs.Limit(-1).ValuesFlat(&l, "Busyid")
	if err != nil || len(l) < 1 {
		return nil, err
	}
	ts := o.QueryTable(bname).Filter("Id__in", l).OrderBy("-utime")
	if bname == "sf_sfyy" {
		ts = ts.Filter("jy_type", user.JdType)
	}
	var e []orm.Params
	_, err = ts.Values(&e)
	return e, err
}

// SetBusyStart 设置业务流程状态为流程开始
func SetBusyStart(busyid, bname string) (err error) {
	o := orm.NewOrm()
	ts := o.QueryTable(bname).Filter("Id", busyid)

	_, err = ts.Update(orm.Params{
		"status": 2,
	})
	return
}
func SetBusyEnd(busyid, bname string, res int) (err error) {
	flag := 3
	if res == 1 {
		flag = 3
	} else {
		flag = 0
	}
	o := orm.NewOrm()
	ts := o.QueryTable(bname).Filter("Id", busyid)

	_, err = ts.Update(orm.Params{
		"status": flag,
	})

	return
}

// GetStateinsByBusy 根据业务id获取状态实例
func GetStateinsByBusy(busyid string) (stateInses []Stateinstance, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance))
	qs = qs.Filter("Busyid", busyid).OrderBy("Ctime")
	_, err = qs.Limit(-1).All(&stateInses)
	return
}

// GetCurrentByUser 根据用户id和业务名称获取待办信息
func GetCurrentByUser(userid, busyid string) (*Stateinstance, error) {
	o := orm.NewOrm()
	var st Stateinstance
	beego.Debug(userid, busyid)
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", userid).Filter("Busyid", busyid)
	err := qs.Filter("Status", 1).One(&st)

	return &st, err
}

// GetCurrent 根据用户id和业务名称获取待办信息
func GetCurrent(busyid string) (*Stateinstance, error) {
	o := orm.NewOrm()
	var st Stateinstance
	qs := o.QueryTable(new(Stateinstance)).Filter("Busyid", busyid)
	err := qs.Filter("Status", 1).One(&st)

	return &st, err
}

// 自动生成下一步可能流程状态实例
func autoGenerateStateInstance(o orm.Ormer, flow *Flowinstance, formStateInstance *Stateinstance, user *User) error {
	//o := orm.NewOrm()
	//o.Begin()
	// 查询 transition
	var list orm.ParamsList
	if _, err := o.QueryTable(new(Transition)).Filter("Isdelete", 0).Filter("From", formStateInstance.State.Id).
		ValuesFlat(&list, "to"); err != nil {
		beego.Debug(err)
		//o.Rollback()
		return err
	}
	// 查询to state
	var states []State
	if _, err := o.QueryTable(new(State)).Filter("Isdelete", 0).Filter("Id__in", list).All(&states); err != nil {
		beego.Debug(err)
		//o.Rollback()
		return err
	}
	// 生成下一步stateInstance
	for _, val := range states {
		ins := NewStateinstance()
		SyncStateAndStateInstance(&val, ins)
		ins.Flowinstance = flow
		ins.Creater = user.Name
		ins.Updater = user.Name
		ins.State = &val
		ins.Busyid = flow.Busyid
		ins.Busyname = flow.Busyname
		switch val.Classname {
		case "start":
			ins.UserId = user.Id
			flow.Start = ins.Id
			flow.Currentstate = ins.Id
			ins.Status = 1
		case "end":
			ins.UserId = ""
			flow.End = ins.Id
		case "join":
			ins.UserId = ""
		case "fork":
			ins.UserId = ""
		case "auto":
			ins.UserId = ""
		default:
			switch val.Type {
			case 0:
				ins.UserId = ""
			case 1:
				us, err := GetUserByOrgRoel(user.Organization.Id, val.RoleId)
				beego.Debug(us)
				if err != nil {
					beego.Error(err)
					//o.Rollback()
					return err
				}
				ins.UserId = us.Id
			case 2:
				// 将角色Id赋值，查询制应添加按角色查询的条件
				ins.UserId = val.RoleId
			case 3:
				var list orm.ParamsList
				if _, err := o.QueryTable(flow.Busyname).Filter("Id", flow.Busyid).
					ValuesFlat(&list, val.Key); err != nil {
					beego.Debug(err)
					//o.Rollback()
					return err
				}
				beego.Debug(list)
				if len(list) != 1 {
					err := errors.New("授权类型与KEY值设置有误！")
					beego.Debug(err)
					//o.Rollback()
					return err
				}
				ins.UserId = fmt.Sprint(list[0])
			default:
				ins.UserId = ""
			}
			//if flow.Busyname == "sf_case" {
			//	users, err := GetUserByOrgRoelList(user.Organization.Id, val.RoleId)
			//	beego.Debug(users)
			//	if err != nil {
			//		beego.Error(err)
			//		o.Rollback()
			//		return err
			//	}
			//	deepuser, _ := GetUserById(users[0].Id)
			//	ins.UserId = deepuser.Role[0].Id
			//} else if flow.Busyname == "ims_approve" {
			//
			//} else {
			//	us, err := GetUserByOrgRoel(user.Organization.Id, val.RoleId)
			//	beego.Debug(us)
			//	if err != nil {
			//		beego.Error(err)
			//		o.Rollback()
			//		return err
			//	}
			//	ins.UserId = us.Id
			//}
		}
		_, err := o.Insert(ins)
		if err != nil {
			beego.Error(err)
			//o.Rollback()
			return err
		}
	}
	return nil
}

func autoGenerateStateInstanceAndTransitionInstance(o orm.Ormer, flow *Flowinstance,
	formStateInstance *Stateinstance, user *User, args map[string]interface{}) error {
	var list orm.ParamsList
	if _, err := o.QueryTable(new(Transition)).Filter("Isdelete", 0).Filter("From", formStateInstance.State.Id).
		ValuesFlat(&list, "to"); err != nil {
		beego.Debug(err)
		//o.Rollback()
		return err
	}
	beego.Debug(list)
	// 查询to state
	var states []State
	if _, err := o.QueryTable(new(State)).Filter("Isdelete", 0).Filter("Id__in", list).All(&states); err != nil {
		beego.Debug(err)
		//o.Rollback()
		return err
	}

	// 生成下一步stateInstance
	idArray := make([]string, 0)
	for _, val := range states {
		ins := NewStateinstance()
		SyncStateAndStateInstance(&val, ins)
		idArray = append(idArray, ins.Id)
		ins.Flowinstance = flow
		ins.Creater = user.Name
		ins.Updater = user.Name
		ins.State = &val
		ins.Busyid = flow.Busyid
		ins.Busyname = flow.Busyname
		switch val.Classname {
		case "start":
			ins, _ := GetStateinstanceByFlowInsAndState(flow.Id, val.Id)
			idArray[len(idArray)-1] = ins.Id
			continue
		case "end":
			ins.UserId = ""
			flow.End = ins.Id
		case "join":
			ins.UserId = ""
		case "fork":
			ins.UserId = ""
		case "auto":
			ins.UserId = ""
		case "dispatch":
			switch val.Type {
			case 0:
				ins.UserId = ""
			case 1:
				us, err := GetUserByDeptRoleRewrite(user.Dept[0].Id, val.RoleId)
				beego.Debug("????????????????????")
				beego.Debug(us)
				if err != nil {
					beego.Error(err)
					//o.Rollback()
					return err
				}
				ins.UserId = us.Id
			case 2:
				ins.UserId = val.RoleId
			case 3:
				//groupId := getRemarkFromArgs(args)
				//leader, err := QueryLeaderUserByProfessorGroupId(o, groupId)
				//if err != nil {
				//	beego.Debug(err)
				//	//o.Rollback()
				//	return err
				//}
				ins.UserId = ""
			case 4:

				ins.UserId = ""
			default:
				ins.UserId = ""
			}

		case "task":
			switch val.Type {
			// 将UserID设置为空
			case 0:
				ins.UserId = ""
			// 只允许当前角色有一个用户，并赋值该用户的ID
			case 1:
				us, err := GetUserByDeptRoleRewrite(user.Dept[0].Id, val.RoleId)
				beego.Debug(us)
				if err != nil {
					beego.Error(err)
					//o.Rollback()
					return err
				}
				ins.UserId = us.Id
			// 将角色Id赋值，查询制应添加按角色查询的条件
			case 2:
				ins.UserId = val.RoleId
			// 将UserID设置为用户制定的值
			case 3:
				var list orm.ParamsList
				if _, err := o.QueryTable(flow.Busyname).Filter("Id", flow.Busyid).
					ValuesFlat(&list, val.Key); err != nil {
					beego.Debug(err)
					//o.Rollback()
					return err
				}
				beego.Debug(list)
				if len(list) != 1 {
					err := errors.New("授权类型与KEY值设置有误！")
					beego.Debug(err)
					//o.Rollback()
					return err
				}
				ins.UserId = fmt.Sprint(list[0])
			// 重复的操作，注释
			//case 4:
			//	us, err := GetUserByDeptRoleRewrite(user.Dept[0].Id, val.RoleId)
			//	beego.Debug(us)
			//	if err != nil {
			//		beego.Error(err)
			//		//o.Rollback()
			//		return err
			//	}
			//	ins.UserId = us.Id
			//case 5:
			//	ins.UserId = val.RoleId

			// 将UserID设置为空
			default:
				ins.UserId = ""
			}
		default:

		}
		_, err := o.Insert(ins)

		if err != nil {
			beego.Error(err)
			//o.Rollback()
			return err
		}
		if ins.UserId != "" {
			if err := NewMessageWithTransaction(o, flow, ins); err != nil {
				o.Rollback()
				return err
			}
		}
		// 生成对应的transitionInstance
	}
	var statesIns []Stateinstance
	if _, err := o.QueryTable(new(Stateinstance)).Filter("Id__in", idArray).All(&statesIns); err != nil {
		beego.Debug(err)
		//o.Rollback()
		return err
	}
	for _, val := range statesIns {
		if err := autoGenerateTransitionInstanceUseUserId(o, flow, formStateInstance, &val, user); err != nil {
			beego.Debug(err)
			return err
		}
	}

	return nil
}

// 将stateinstance 标记为不执行
// 根据当前根据当前state查询其它stateInstance查询其它stateInstance
func UpdateOtherStateInstanceStatusTo3(o orm.Ormer, from, to string) error {
	sql := `
UPDATE fsm_stateinstance SET status=3 WHERE "id" IN
(
	SELECT "to" FROM fsm_transitioninstance WHERE "from"=? AND "to" != ? 
)
`
	_, err := o.Raw(sql, from, to).Exec()
	if err != nil {
		return err
	}
	return nil
}

func newTaskInstance() *Stateinstance {
	return &Stateinstance{
		Id:        libs.UUID(),
		Ctime:     time.Now(),
		Utime:     time.Now(),
		Classname: "task",
		Status:    0,
	}
}

func newJoinInstance() *Stateinstance {
	return &Stateinstance{
		Id:        libs.UUID(),
		Ctime:     time.Now(),
		Utime:     time.Now(),
		Classname: "join",
		Text:      "会签",
		Updater:   " ",
		Creater:   " ",
		Status:    1,
		Isdelete:  0,
	}
}

func newForkInstance() *Stateinstance {
	return &Stateinstance{
		Id:        libs.UUID(),
		Ctime:     time.Now(),
		Utime:     time.Now(),
		Classname: "fork",
		Text:      "分派",
		Updater:   " ",
		Creater:   " ",
		Status:    1,
		Isdelete:  0,
	}
}
